<!-- 作者:高翔宇 时间:2024/5/30 周四 16:58 -->
<script setup lang="ts">
import {onMounted, reactive, ref, watch} from 'vue'
import {Delete, RefreshRight} from "@element-plus/icons-vue";
import type {UploadProps, UploadUserFile} from 'element-plus'
import {ElMessage} from 'element-plus';
import {useMediaStore} from "@/store/modules/media";
import {useUserStore} from "@/store";
import {useSettingStore} from "@/store/setting.ts";
import {MaterialImage} from "@/api/media/type.ts";

const settingStore = useSettingStore();
const loading = reactive({
  materialListCard: false
})

const pageParam = reactive({
  // 当前页码
  pageNum: 1,
  // 每页显示条目个数
  pageSize: 10,
})
// 分页组相关配置
const paginationSettings = reactive({
  // 分页组件是否使用小型分页样式
  small: true,
  // 分页组件是否显示背景色
  background: false,
  // 分页组件禁用状态
  disabled: false,
  pageSizes: [5, 10, 20, 30, 40, 50, 100]
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

const fileList = ref<UploadUserFile[]>([])

/**
 * 上传文件改变时的钩子
 */
const handleChange: UploadProps['onChange'] = () => {
  fileList.value = fileList.value.slice(-10);
}

/**
 * 上传成功回调
 */
const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  console.log('handleUploadSuccess', response)
  if (response.code !== 200) {
    console.log('上传失败。response', response)
    ElMessage.error(response.message)
  } else {
    ElMessage.success('上传成功')
    getMediaList()
  }
}

/**
 * 点击文件列表中已上传的文件时的钩子
 */
const handleOnPreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log('handleOnPreview', uploadFile)
}

const mediaStore = useMediaStore();

/**
 * 获取媒体图片列表
 */
function getMediaList() {
  if (!settingStore.previewing) mediaStore.clearMaterialInfo()
  loading.materialListCard = true
  mediaStore.pageQuery(pageParam)
      .then(() => {
        mediaStore.materialInfo.mediaImageList.forEach(item => {
          item.showButton = false
        })
      })/*.catch((reason) => {
    ElMessage.error(reason.message)
  })*/.finally(() => {
    loading.materialListCard = false
  })
}

// 监听分页参数变化
watch(pageParam, () => {
  getMediaList()
}, {
  deep: true,
  immediate: true
})

/**
 * 删除素材
 */
function deleteMaterial(item: MaterialImage) {
  ElMessageBox.confirm('确定删除该素材吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    mediaStore.deleteMaterialById(item.id).then(() => {
      ElMessage.success('删除成功')
      getMediaList()
    }).catch(() => {
      ElMessage.error("删除失败")
    })
  })
}

onMounted(() => {
  console.log('onMounted')
})

/**
 * 将数组转换为二维数组
 *
 * @param arr 数组
 * @param n 每一行有多少个元素
 */
function to2DArray(arr: any[], n: number): any[][] {
  if (!Array.isArray(arr) || !Number.isInteger(n) || n <= 0) {
    throw new Error('Invalid arguments. arr must be an array of numbers and n must be a positive integer.');
  }

  let twoDArray: any[][] = [];
  let chunk: any[];

  while (arr.length > 0) {
    chunk = arr.slice(0, n); // 取出前 n 个元素
    arr = arr.slice(n); // 移除前 n 个元素
    twoDArray.push(chunk); // 将 chunk 添加到二维数组中
  }
  return twoDArray;
}
</script>

<template>
  <el-row style="display: flex; justify-content: right">
    <el-upload
        action="http://localhost:5603/api/media/material/upload"
        :on-success="handleUploadSuccess"
        :on-change="handleChange"
        :headers="{'token': useUserStore().userState.token}"
        name="material"
        multiple
        drag
        :on-preview="handleOnPreview"
        :on-error="() => ElMessage.error('上传失败')"
        :show-file-list="false"
    >
      <el-button type="primary">上传图片</el-button>
      <template #tip>
        <div class="el-upload__tip">
          支持拖拽上传~
        </div>
      </template>
    </el-upload>
  </el-row>
  <el-divider/>
  <el-row style="width: 100%;">
    <el-empty description="什么也没有诶~"
              v-show="mediaStore.materialInfo.mediaImageList.length === 0 && !loading.materialListCard"
              style="margin: auto;">
      <el-button @click="getMediaList()" :icon="RefreshRight" type="info" circle/>
    </el-empty>
    <el-scrollbar
        v-show="!(mediaStore.materialInfo.mediaImageList.length === 0 && !loading.materialListCard)"
        v-loading="loading.materialListCard"
        :element-loading-spinner="settingStore.svg"
        element-loading-background="#ffffff"
        :height="mediaStore.materialInfo.total > 12 || mediaStore.materialInfo.total <= 0 ? '35vh':'auto'"
        style="width: 100%; margin: auto;">
      <div v-for="(oneDArr, index) in to2DArray(mediaStore.materialInfo.mediaImageList,6)"
           :key="index" style="display: flex;"
           :style="{'justify-content': 'space-between'}">
        <div v-for="item in oneDArr" :key="item.id"
             style="display: inline-block; border: 1px solid #f5f5f5; padding: 10px; margin: 20px;">
          <div style="position: relative" class="img" @mouseover="item.showButton = true;"
               @mouseleave="item.showButton = false">
            <el-image :src="item.url" fit="cover" style="width: 100px; height: 100px;"/>
            <div v-show="item.showButton"
                 style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5);">
              <el-button style="position: absolute; top: 60%; left: 60%"
                         type="danger" circle plain :icon="Delete" @click="deleteMaterial(item)"/>
            </div>
          </div>
          <div
              style="text-align: center; margin-top: 5px;font-weight: bolder; font-family: 宋体,'Microsoft YaHei', serif">
            {{ item.imageName }}
          </div>
        </div>
        <div
            style="display: inline-block; border: 1px; padding: 10px; margin: 20px; width: 100px; height: 100px;"
            v-for="item in 6 - oneDArr.length"
            :key="item">
        </div>
      </div>
    </el-scrollbar>
  </el-row>
  <div v-show="mediaStore.materialInfo.total > 0 && !loading.materialListCard"
       style="display: flex; justify-content: center; margin-top: 20px;">
    <el-pagination
        v-model:current-page.sync="pageParam.pageNum"
        v-model:page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="paginationSettings.pageSizes"
        :small="paginationSettings.small"
        :disabled="paginationSettings.disabled"
        :default-current-page="pageParam.pageNum"
        :background="paginationSettings.background"
        :total="mediaStore.materialInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped lang="scss">
</style>
